package com.cqut.forum.action;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cqut.forum.entity.User;
import com.cqut.forum.service.UserService;
import com.cqut.forum.util.ResponsePrintWriter;

/**
 * 用户注册action
 * @author yangxun
 */
@Controller
public class RegisterAction {
	
	private User user;
	@Resource
	private UserService userService;
	
	@RequestMapping("/main/register_checkName")
	public void checkName(HttpServletRequest request,HttpServletResponse response,
			String userName){
		String result = null;
		if(userService.getByName(userName)!=null){
			result = "对不起，该名称已经存在";
		}
		else{
			result = "恭喜你，该名称可以使用";
		}
		ResponsePrintWriter.printWriterString(response, result);
	}
	
	@RequestMapping("/main/register")
	public String register(HttpServletRequest request,User user) throws ServletException, IOException{
		String checked = checkUser(user);
		
		if(!checked.equals("")){
			//用户信息不正确
			//map.put("result", checked);
			return "error.html";
		}
		if(request.getSession().getAttribute("user")==null
				&&userService.getByName(user.getUserName())==null){
			userService.register(user);
			request.getSession().setAttribute("user", user);
		}
		//用户信息正确
		//request.getRequestDispatcher("/user_main").forward(request,response);
		return "/pages/user/user_main.html";
		//return null;
	}
	
	private String checkUser(User user){
		String result = "";
		if(user == null||user.getUserName() == null ||user.getUserPassword() == null
		 ||user.getUserEmail() == null||user.getUserSex()==null){
			result = "信息传输遗失，请重新注册";
		}
		else if(user.getUserName().equals("")||user.getUserPassword().equals("")||
				user.getUserEmail().equals("")||user.getUserSex().equals("")){
			result = "用户信息不能为空";
		}
		else if(user.getUserName().matches("[/w]")){
			result = "用户名只能为字母和数字";
		}
		else if(user.getUserPassword().matches("[/w]")){
			result = "密码只能为数字和字母";
		}
		else if(user.getUserEmail().matches("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])")){
			result = "邮箱格式不正确";
		}
		return result;
	}
	/*********get and set method************/
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public UserService getUserService() {
		return userService;
	}
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}
